import { Controller, Get, Param, Query, Body, Post, Sse } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { Public } from '../../../../../common/public.decorator';
import { validatePostBodyDto } from './demo.create.dto';
import { Subject, interval, map } from 'rxjs';
import { WebsocketsGateway } from '../../events/websockets/websockets.gateway';

@Controller('demo')
export class DemoController {
  constructor(
    private readonly eventEmitterService: EventEmitter2,
    private readonly ws: WebsocketsGateway,
  ) {}
  @Public()
  @Get('noLoginRequest')
  sendMsg() {
    return 'noLoginRequest';
  }

  @Get('loginRequirRequest')
  sendLoginInfo() {
    return 'loginRequirRequest';
  }

  @Public()
  @Get('validateGetParameter/:id')
  async validateGetParameter(
    @Param('id') id: string,
    @Query() query: Record<string, any>,
  ) {
    return {
      code: 200,
      data: {
        params: id,
        query,
      },
      msg: '没法验证get参数',
    };
  }

  @Public()
  @Post('validatePostParameter')
  async validatePostParameter(@Body() body: validatePostBodyDto) {
    return {
      code: 200,
      data: body,
      msg: 'body校验通过',
    };
  }

  // 消息推送SSE是常用的服务器消息通信手段，适用于服务器主动给客户端发送消息的场景
  @Public()
  @Sse('sseTest')
  async sseTest() {
    return interval(5000).pipe(
      map((value) => ({ data: 'hello world-' + value })),
    );
  }

  // 1,先建立链接 2，发送自定义消息
  // 1，先建立链接
  @Public()
  @Sse('sseMsg')
  sendServerEvent() {
    const subject = new Subject();

    // 监听CUSTOM_MESSAGE事件
    this.eventEmitterService.on('CUSTOM_MESSAGE', (data) => {
      console.log(data, 'sseMsg');
      // subject 处理事件
      subject.next(data);
    });

    return subject.pipe(
      map((data: MessageEventData): { data: MessageEventData } => ({
        data: data,
      })),
    );
  }

  // 2，发送自定义消息
  @Public()
  @Get('sendCustomMsg')
  sendCustomMsg(
    @Query('username') username: string,
    @Query('age') age: number,
  ) {
    const messageEventData: MessageEventData = {
      username,
      age,
      message: { hi: '你好乐闻' },
    };
    // 发送 CUSTOM_MESSAGE 事件
    this.eventEmitterService.emit('CUSTOM_MESSAGE', messageEventData);
    return {
      data: 'ok',
    };
  }

  @Public()
  @Get('webSocketTest')
  webSocketTest() {
    try {
      const ls = this.ws.server.emit('onMessage', '穷哈哈哈');
      if (ls === true) {
        return {
          code: 200,
          data: true,
          msg: '发送成功',
        };
      }
      return {
        code: 500,
        data: false,
        msg: '发送失败',
      };
    } catch (error) {
      return {
        code: 500,
        data: false,
        msg: '发送失败',
      };
    }
  }

  // 监听数据
  @OnEvent('CUSTOM_MESSAGE')
  onCustomMessage(messageEventData: MessageEventData) {
    console.log(messageEventData, '监听到了');
  }
}

export interface MessageEventData {
  username: string;
  age: number;
  message: Record<string, string>;
}
